package com.zzb.rabbit.rabbitproduce.controller;

import com.zzb.rabbit.rabbitproduce.annotation.LogTest;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author zhuzubin
 * @Date 2019/12/9 15:07
 */
@RestController
public class SendMessageController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @LogTest("发送队列消息")
    @PostMapping("sendDirectMessage")
    public String sendDirectMessage() {
        Map<String,Object> map = this.getSendMap(String.valueOf(UUID.randomUUID()), "message: test message, hello!");
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        map.put("createTime",createTime);
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);
        return "ok";
    }

    @PostMapping("/sendTopicMessage1")
    public String sendTopicMessage1() {
        rabbitTemplate.convertAndSend("topicExchange", "topic.man", this.getSendMap(
                String.valueOf(UUID.randomUUID()), "message: M A N "
        ));
        return "ok";
    }

    @PostMapping("/sendTopicMessage2")
    public String sendTopicMessage2() {
        rabbitTemplate.convertAndSend("topicExchange", "topic.woman", this.getSendMap(
                String.valueOf(UUID.randomUUID()), "message: woman is all "
        ));
        return "ok";
    }

    private Map<String, Object> getSendMap(String messageId, String messageData) {
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        return map;
    }
}
